package com.example.weather;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.weather.model.Constants;
import com.example.weather.model.PlaceResponse;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.List;

public class WelcomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        //实例化控件
        ImageView imageView = findViewById(R.id.welcome_image);

        //2500毫秒后跳转主界面
        imageView.postDelayed(() -> {
            getData("高明");
        }, 2500);
    }
    private final Gson gson = new Gson();
    private void getData(String adress){
        //网络请求用户所输入的地址信息
        OkGo.<String>get(Constants.SEARCH_PLACE)
                .params("query", adress.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //通过gson解析json数据
                        PlaceResponse placeResponse = gson.fromJson(response.body(), PlaceResponse.class);
                        //判断是否请求成功
                        if (placeResponse.getStatus().equals("ok")) {
                            //拿到数据后刷新recyclerView数据
                            List<PlaceResponse.Place> places = placeResponse.getPlaces();
                            Intent intent = new Intent(WelcomeActivity.this, WeatherActivity.class);
                            //将place信息填入intent内
                            intent.putExtra(Constants.WEATHER, new Gson().toJson(places.get(0)));
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(WelcomeActivity.this, "没有找到相关地区", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}